<template>
  <view class="shop-create">
    <uni-forms ref="shopForm" :rules="rules" @submit="handleCreateShop">
      <!-- 图片上传 -->
      <view class="addimage">
        <view>图片上传</view>
        <view style="margin-top: 20rpx;">
          <view v-if="shop.shopLogo" class="img-wrapper">
            <image style="width: 100%; height: 100%;" :src="shop.shopLogo"></image>
            <view class="close-icon" @click.stop="delImg">
              <uni-icons type="closeempty" size="20"></uni-icons>
            </view>
          </view>
          <view
            v-else
            class="camera"
            @click="chooseImage"
          >
            <uni-icons type="camera" size="40"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 店铺名称 -->
      <uni-forms-item label="店铺名称" required>
        <uni-easyinput
          v-model="shop.shopName"
          :inputBorder="false"
          placeholder="请输入店铺名称"
        />
      </uni-forms-item>

      <!-- 店铺描述 -->
      <uni-forms-item label="店铺描述" required>
        <uni-easyinput
          v-model="shop.shopDescription"
          :inputBorder="false"
          type="textarea"
          placeholder="请输入店铺描述"
        />
      </uni-forms-item>

      <!-- 店铺状态切换 -->
      <view class="status-toggle">
        <text>店铺状态：</text>
        <button
          :class="shop.shopStatus === 0 ? 'active-button' : 'inactive-button'" 
          @click="toggleShopStatus"
        >
          {{ shop.shopStatus === 0 ? '开启中' : '已停用' }}
        </button>
      </view>

      <!-- 提交按钮 -->
      <view class="form-group">
        <button @click="submitForm" class="submit-button">确认修改</button>
      </view>
    </uni-forms>
  </view>
</template>


<script>
import { updateShop } from "@/api/shop/index.js";

export default {
  data() {
    return {
      shop: {
        userId: 1,
        shopName: "",
        shopDescription: "",
        shopLogo: null, // 存储本地选择的图片路径
        shopStatus: 0, // 0 为开启，1 为停用
      },
    };
  },
  onLoad(options) {
    // 解析 options，将 shopInfo 填入表单
    if (options.shopInfo) {
      try {
        const shopInfo = JSON.parse(decodeURIComponent(options.shopInfo));
        this.shop.shopName = shopInfo.shopName || "";
        this.shop.shopDescription = shopInfo.shopDescription || "";
        this.shop.shopLogo = shopInfo.shopLogo || null;
        this.shop.userId = shopInfo.userId || 1; // 默认 userId 为 1
        this.shop.shopStatus = shopInfo.shopStatus || 0; // 默认状态为开启
      } catch (err) {
        console.error("解析 shopInfo 失败:", err);
        uni.showToast({ title: "店铺信息加载失败", icon: "none" });
      }
    }
  },
  methods: {
    // 切换店铺状态
    toggleShopStatus() {
      this.shop.shopStatus = this.shop.shopStatus === 0 ? 1 : 0;
      const statusText = this.shop.shopStatus === 0 ? "店铺已开启" : "店铺已停用";
      uni.showToast({ title: statusText, icon: "none" });
    },
   async uploadImage(filePath) {
     // 如果是服务器图片 (URL 格式)，直接返回
     if (filePath.startsWith("http")) {
       console.log("服务器图片，无需上传:", filePath);
       return filePath;
     }
   
     // 否则上传本地图片
     console.log("上传本地图片:", filePath);
     return new Promise((resolve, reject) => {
       uni.uploadFile({
         url: 'http://localhost:8080/shop/upload', // 上传接口
         filePath: filePath, // 本地路径
         name: 'file', // 文件字段名
         success: (uploadResult) => {
           try {
             const res = JSON.parse(uploadResult.data);
             if (res.url) {
               console.log("图片上传成功，返回 URL:", res.url);
               resolve(res.url);
             } else {
               uni.showToast({ title: '图片上传失败，未返回 URL', icon: 'none' });
               reject(new Error('图片上传失败，未返回 URL'));
             }
           } catch (error) {
             console.error('JSON 解析失败:', error);
             uni.showToast({ title: '图片上传失败', icon: 'none' });
             reject(error);
           }
         },
         fail: (err) => {
           console.error('图片上传失败:', err);
           uni.showToast({ title: '图片上传失败', icon: 'none' });
           reject(err);
         },
       });
     });
   },
   
  // 选择图片
  async chooseImage() {
    const _this = this; // 保存 Vue 实例的上下文
    uni.chooseImage({
      count: 1, // 限制上传的图片数量
      sizeType: ["compressed"], // 图片压缩类型
      sourceType: ["album", "camera"], // 图片来源
      success: function (res) {
        if (res.tempFilePaths && res.tempFilePaths.length > 0) {
          _this.shop.shopLogo = res.tempFilePaths[0]; // 使用 _this 代替 this
          uni.showToast({ title: "图片选择成功", icon: "none" });
          console.log("图片路径:", res.tempFilePaths[0]);
        } else {
          uni.showToast({ title: "未选择图片", icon: "none" });
          console.warn("未返回有效图片路径");
        }
      },
      fail: function (err) {
        uni.showToast({ title: "选择图片失败", icon: "none" });
        console.error("选择图片失败：", err);
      },
    });
  },

    delImg() {
      this.shop.shopLogo = null; // 将图片路径清空
      uni.showToast({ title: "图片已删除", icon: "none" });
    },
    // 提交表单
    async submitForm() {
      if (!this.shop.shopName || !this.shop.shopDescription) {
        uni.showToast({ title: "请完善信息", icon: "none" });
        return;
      }
    
      if (!this.shop.shopLogo) {
        uni.showToast({ title: "请上传一张图片", icon: "none" });
        return;
      }
    
      try {
        const imageUrl = await this.uploadImage(this.shop.shopLogo);
        if (!imageUrl) {
          uni.showToast({ title: "图片上传失败，请重试", icon: "none" });
          return;
        }
    
        // 更新 shop 对象的图片 URL
        this.shop.shopLogo = imageUrl;
    
        // 提交表单数据
        const response = await updateShop(this.shop);
        console.log(response);
    
        uni.showToast({ title: "店铺修改成功", icon: "success" });
       
      } catch (error) {
        console.error("失败:", error);
        uni.showToast({ title: "网络错误，请稍后重试", icon: "none" });
      }
    },
  },
};
</script>


<style lang="scss" scoped>
.shop-create {
  padding: 16px;

  .addimage {
    margin-bottom: 20px;

    .img-wrapper {
      display: inline-block;
      position: relative;
      width: 100px;
      height: 100px;
      margin-right: 10px;

      .close-icon {
        position: absolute;
        top: -5px;
        right: -5px;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        color: white;
        padding: 5px;
      }
    }

    .camera {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      width: 100px;
      height: 100px;
      background: #f0f0f0;
      border: 1px dashed #ccc;
      border-radius: 4px;
    }
  }

  .form-group {
    margin-top: 20px;
  }

  .submit-button {
    width: 100%;
    padding: 10px;
    font-size: 16px;
    color: #fff;
    background-color: #007bff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    text-align: center;
  }

  .submit-button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }
}
.status-toggle {
  margin: 20rpx 0;
  display: flex;
  align-items: center;
}
.active-button {
  background-color: #4caf50;
  width: 250px;
  color: white;
  padding: 10rpx 20rpx;
  border-radius: 5rpx;
  border: none;
}
.inactive-button {
	width: 250px;
  background-color: #f44336;
  color: white;
  padding: 10rpx 20rpx;
  border-radius: 5rpx;
  border: none;
}
</style>
